package com.accesshollywood.components;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JOptionPane;

import org.jdesktop.swingx.JXHyperlink;

public class FileFolderLink extends JXHyperlink {
	private String	filename;
	public boolean	isActive	= false;
	private boolean	isFile		= false;

	public FileFolderLink() {
		super();
	}

	public void setLink(String str) {
		if (str.equals("")) {
			isActive = false;
		} else {
			filename = str;
			if (!filename.contains("http")) {
				File file = new File(str);
				setURI(file.toURI());
				isFile = true;
			} else {
				try {
					setURI(new URI(filename));
				} catch (URISyntaxException e) {
					e.printStackTrace();
				}
			}

			setAction(new LinkAction());
			setToolTipText(filename);
			isActive = true;
		}
	}

	public class LinkAction extends AbstractAction {
		public LinkAction() {
			super();
			if (isFile) {
				super.putValue(Action.NAME, "OPEN FOLDER");
			} else {
				super.putValue(Action.NAME, "OPEN LINK IN BROWSER");
			}
			super.putValue(Action.SHORT_DESCRIPTION, "Opens the Folder");
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			Runtime r = Runtime.getRuntime();
			if (isFile) {
				File file = new File(filename);
				if (file.exists()) {
					try {
						r.exec("explorer.exe \"" + file.getAbsolutePath() + "\"");
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				} else {
					JOptionPane.showMessageDialog(null, "WARNING!\nFOLDER   " + file.getAbsolutePath() + "   NOT FOUND.", "ERROR", JOptionPane.ERROR_MESSAGE);
				}
			} else {
				try {
					r.exec("explorer.exe \"" + filename + "\"");
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}

	}
}
